﻿package 
{
	import flash.display.MovieClip;
	import flash.events.Event;

	public class Arrow extends MovieClip 
	{
		public var Active:Boolean;
		public var TargetIndex:int;
		public var Target:MovieClip;
		
		public function Arrow() 
		{
			addEventListener(Event.ENTER_FRAME, EnterFrame);
			addEventListener(Event.REMOVED, Unload);
			init();
		}
		
		private function init():void
		{
			Active = false;
		}
		
		public function InitializeValues():void
		{
			TargetIndex = 1;
			Active = true;
		}
		
		private function EnterFrame(event:Event):void
		{
			if (Active)
			{
				this.visible = true;
				
				var tempBattle:Battle = this.parent as Battle;
				var searchForward:Boolean = true;
				var searching:Boolean = false;
				if (Game.LeftIsPressed)
				{
					searchForward = false;
					searching = true;
				}
				else if (Game.RightIsPressed)
				{
					searchForward = true;
					searching = true;
				}
				
				var tempTarget:MovieClip;
				var originalIndex:int = TargetIndex;
				while(searching)
				{
					if (searchForward)
					{
						TargetIndex++;
						if (TargetIndex > 6)
						{
							TargetIndex = 1;
						}
					}
					else
					{
						TargetIndex--;
						if (TargetIndex < 1)
						{
							TargetIndex = 6;
						}
					}
					
					tempTarget = getTargetClip(tempBattle);
					
					if (tempTarget.numChildren > 0)
					{
						Target = tempTarget;
						searching = false;
					}
					if (originalIndex == TargetIndex)
					{
						searching = false;
					}
				}
				
				if (Target == null)
				{
					Target = getTargetClip(tempBattle);
				}
				
				var enemy:MovieClip = Target.getChildAt(0) as MovieClip;
			
				this.x = (Target.x - enemy.width);
				this.y = (Target.y - enemy.height);
				
				if (Game.ZIsPressed)
				{
					tempBattle.PerformedAction(true, Target);
					this.Active = false;
					this.visible = false;
				}
			}
			else
			{
				this.visible = false;
			}
		}
		
		private function getTargetClip(tempBattle:MovieClip):MovieClip
		{
			switch(TargetIndex)
			{
				case 1: return tempBattle.e1holder; break;
				case 2: return tempBattle.e2holder; break;
				case 3: return tempBattle.e3holder; break;
				case 4: return tempBattle.e4holder; break;
				case 5: return tempBattle.e5holder; break;
				case 6: return tempBattle.e6holder; break;
			}
			return null;
		}
		
		private function Unload(event:Event):void
		{
			if (event.target.name == this.name)
			{
				removeEventListener(Event.ENTER_FRAME, EnterFrame);
			}
		}
	}
}